import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { fr } from 'element-plus/es/locales.mjs'

const routes = [
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'dashboard', requiresAuth: true }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user/index.vue'),
        meta: { title: '用户管理', icon: 'user', requiresAuth: true }
      },
      {
        path: 'system',
        name: 'System',
        component: () => import('@/views/system/index.vue'),
        meta: { title: '系统设置', icon: 'setting', requiresAuth: true }
      },
      {
        path: 'admin/assess',
        name: 'AdminAssess',
        component: () => import('@/views/assess/admin/AssessManage.vue'),
        meta: { title: '管理端评价'}
      },
      {
        path: 'course',
        name: 'Course',
        component: () => import('@/views/course/index.vue'),
        meta: { title: '商品管理', icon: 'course', requiresAuth: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  try {
    const userStore = useUserStore()
    const token = userStore.token

    // 设置页面标题
    document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '后台管理系统'
    
    // 判断是否需要登录权限
    if (from.path === '/login' || to.path === '/login') {
      next();
      return;
    }
    
    if (!token) {
      // 未登录，重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
      return;
    }
    
    // 已登录，获取用户信息
    await userStore.getUserInfoAction()
    next()
  } catch (error) {
    console.error('Router guard error:', error)
    // 获取用户信息失败，清除token并跳转到登录页
    const userStore = useUserStore()
    userStore.logout()
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }
})

export default router 